package com.dbs.donatebooksystem.controller;

import com.dbs.donatebooksystem.Service.OrderService;
import com.dbs.donatebooksystem.pojo.Ids;
import com.dbs.donatebooksystem.pojo.Orders;
import com.dbs.donatebooksystem.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin(origins = "http://localhost:8080", originPatterns = "http://localhost:8081")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;


    @GetMapping("/getOrder")
    public Result getOrder(){
        List<Orders> list = orderService.getOrder();
        log.info("list:{}",list);
        return Result.success(list);
    }

    @PostMapping("/insertOrder")
    public Result insertOrder(@RequestBody Ids ids){
        log.info("ids:{}",ids);
        orderService.insertOrder(ids);
        return Result.success("提交成功");
    }

    @DeleteMapping("/deleteOrder")
    public Result deleteOrder(@RequestParam Integer orderId){
        log.info("要删除的订单id为:{}",orderId);
        orderService.deleteOrder(orderId);
        return Result.success("删除成功");
    }

    @GetMapping("/getOrderByUserId")
    public Result getOrderByUserId(@RequestParam Integer userId){
        List<Orders> list = orderService.getOrderByUserId(userId);
        log.info("list:{}",list);
        return Result.success(list);
    }

    @PutMapping("/updateOrderStatus/{orderId}/{newStatus}")
    public Result updateOrderStatus(@PathVariable Integer orderId,@PathVariable Integer newStatus) {
        log.info("要修改的订单id为:{} 修改状态为:{}",orderId,newStatus);
        // 验证状态合法性
        if(newStatus < 1 || newStatus > 4) {
            return Result.error("非法状态值");
        }

        Orders orders = orderService.getById(orderId);
        if(orders == null) {
            return Result.error("订单不存在");
        }

        orderService.updateOrderStatus(orderId,newStatus);
        return Result.success("状态更新成功");
    }

    @GetMapping("/SearchOrder")
    public Result SearchOrder(Orders orders){
        List<Orders> ordersList = orderService.selectOrder(orders);
        return Result.success(ordersList);
    }
}
